import { serviceApi, appointmentApi } from "../../utils/api"

// booking.ts
Component({
  data: {
    serviceId: 0,
    serviceName: '',
    servicePrice: 0,
    imageUrl: '',
    selectedDate: '',
    selectedTime: '',
    selectedBeauticianId: 0,
    beauticians: [] as any[],
    customerName: '',
    customerPhone: '',
    remark: '',
    timeSlots: ['09:00', '10:00', '11:00', '14:00', '15:00', '16:00', '17:00'],
    today: ''
  },

  lifetimes: {
    attached() {
      const today = new Date().toISOString().split('T')[0]
      this.setData({
        today,
        selectedDate: today
      })
    }
  },

  methods: {
    onLoad(options: any) {
      // 检查登录状态
      const isLoggedIn = wx.getStorageSync('isLoggedIn')
      const token = wx.getStorageSync('token')
      
      if (!isLoggedIn || !token) {
        console.log('未登录，跳转到登录页面')
        // 使用redirectTo避免返回循环
        wx.redirectTo({
          url: '/pages/login/login'
        })
        return
      }

      const serviceId = parseInt(options.id || '0')
      this.loadServiceInfo(serviceId);
      this.loadBeauticians(serviceId);
    },

    handlerGobackClick() {
      wx.navigateBack({
        delta: 1
      })
    },
    async loadServiceInfo(serviceId: number) {
      // 从页面参数获取服务信息
      try {
        // 调用API获取服务详情
        const response = await serviceApi.getServiceDetail(serviceId)
        if (response.code === 200) {
          this.setData({
            serviceId: response.data.id,
            serviceName: response.data.name,
            servicePrice: response.data.price,
            imageUrl: response.data.imageUrl
          })
        } else {
          throw new Error(response.message)
        }
      } catch (error) {
        wx.showToast({
          title: '获取服务信息失败',
          icon: 'none'
        })
        console.error('获取服务详情失败:', error)
      }
    },

    async loadBeauticians(serviceId: number) {
      try {

        // 调用API获取服务对应的美容师
        const response = await serviceApi.getServiceBeauticians(serviceId)
        if (response.code === 200) {
          this.setData({
            beauticians: response.data || []
          })
        } else {
          throw new Error(response.message)
        }
      } catch (error) {
        console.error('获取美容师列表失败:', error)
        this.setData({
          beauticians: []
        })
      }
    },

    onDateChange(e: any) {
      this.setData({ selectedDate: e.detail.value })
    },

    onTimeSelect(e: any) {
      const time = e.currentTarget.dataset.time
      this.setData({ selectedTime: time })
    },

    onBeauticianSelect(e: any) {
      const beauticianId = parseInt(e.currentTarget.dataset.id)
      this.setData({ selectedBeauticianId: beauticianId })
    },

    onNameInput(e: any) {
      this.setData({ customerName: e.detail.value })
    },

    onPhoneInput(e: any) {
      this.setData({ customerPhone: e.detail.value })
    },

    onRemarkInput(e: any) {
      this.setData({ remark: e.detail.value })
    },

    async submitBooking() {
      if (!this.data.selectedTime) {
        wx.showToast({
          title: '请选择预约时间',
          icon: 'none'
        })
        return
      }

      if (!this.data.selectedBeauticianId) {
        wx.showToast({
          title: '请选择美容师',
          icon: 'none'
        })
        return
      }

      // 保存预约记录
      const booking = {
        projectId: this.data.serviceId,
        appointmentDate: this.data.selectedDate,
        beauticianId: this.data.selectedBeauticianId,
        notes: this.data.remark,
        status: 'pending'
      }

      const response = await appointmentApi.createAppointment(booking)

      console.log(response)
      if (response.code === 200) {
        wx.showModal({
          title: '预约成功',
          content: `您已成功预约 ${this.data.serviceName}，时间：${this.data.selectedDate} ${this.data.selectedTime}`,
          showCancel: false,
          success: () => {
            // 跳转页面
            wx.navigateTo({
              url: '/pages/my-orders/my-orders'
            })
          }
        })
      } else {
        wx.showToast({
          title: '预约失败',
          icon: 'none'
        })
      }
    }
  }
})